package com.ocean.linkedlist;

/**
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/
 */
public class ReverseNodesInKGroup2 {

    public static void main(String[] args) {
        ListNode e5 = new ListNode(5, null);
        ListNode e4 = new ListNode(4, e5);
        ListNode e3 = new ListNode(3, e4);
        ListNode e2 = new ListNode(2, e3);
        ListNode e1 = new ListNode(1, e2);
        ListNode.print(e1);
        ListNode reverse = new ReverseNodesInKGroup2().reverseKGroup(e1, 3);
        ListNode.print(reverse);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) {
            return head;
        }
        ListNode dummy = new ListNode();
        dummy.next =head;
        ListNode cur = dummy;
        ListNode pre = dummy;
        while (cur.next != null) {
            for (int i = 0; i < k && cur != null; i++) {
                // 找到当前组
                cur = cur.next;
            }
            if (cur == null) {
               break; // 说明元素不够一组
            }
            // 将这一组进行调转
            ListNode next = cur.next; // 这是下一组的第一个
            cur.next = null;

            ListNode currentHead = pre.next;

            pre.next = reverse(currentHead); // pre.next 当前组的头  上一组要指向调转后的头

            currentHead.next = next;
            pre = currentHead;
            cur = pre;
        }
        return dummy.next;
    }

    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
